import { useHttp } from "./useHttp";
import { QueryKey, useMutation, useQuery } from "react-query";
import { Task } from "../types/task";
import { TaskType } from "../types/taskType";
import {
  useAddConfig,
  useDeleteConfig,
  useEditConfig,
  useTaskReorderConfig,
} from "./useOptimisticConfig";
import { SortProps } from "./useBillboards";

export const useTasks = (params: Partial<Task>) => {
  const client = useHttp();
  return useQuery<Task[]>(["tasks", params], () =>
    client("tasks", { data: params })
  );
};

export const useTaskTypes = () => {
  const client = useHttp();
  return useQuery<TaskType[]>(["taskTypes"], () => client("taskTypes"));
};

export const useAddTask = (queryKey: QueryKey) => {
  const client = useHttp();
  return useMutation(
    (params: Partial<Task>) =>
      client("tasks", { method: "POST", data: params }),
    useAddConfig(queryKey)
  );
};

export const useEditTask = (queryKey: QueryKey) => {
  const client = useHttp();
  return useMutation(
    (params: Partial<Task>) =>
      client(`tasks/${params.id}`, { method: "PATCH", data: params }),
    useEditConfig(queryKey)
  );
};

export const useDeleteTask = (queryKey: QueryKey) => {
  const client = useHttp();
  return useMutation(
    (id: number) => client(`tasks/${id}`, { method: "DELETE" }),
    useDeleteConfig(queryKey)
  );
};

export const useTask = (id?: number) => {
  const client = useHttp();
  return useQuery<Task>(["tasks", id], () => client(`tasks/${id}`), {
    enabled: Boolean(id),
  });
};

export const useReorderTasks = (queryKey: QueryKey) => {
  const client = useHttp();
  return useMutation(
    (params: SortProps) =>
      client("tasks/reorder", {
        data: params,
        method: "POST",
      }),
    useTaskReorderConfig(queryKey)
  );
};
